<template>
  <div class="announcement-page">
    <el-card class="main-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><Bell /></el-icon>
            <span class="header-title">公告管理</span>
          </div>
          <el-button type="primary" @click="openDialog" :icon="Plus">
            新增公告
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索标题或内容"
          clearable
          style="max-width: 300px;"
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button @click="handleReset" :icon="Refresh">重置</el-button>
      </div>

      <!-- 表格 -->
      <el-table 
        :data="filteredList" 
        border 
        stripe
        v-loading="loading"
        style="width: 100%; margin-top: 20px;"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="priority" label="优先级" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getPriorityType(row.priority)" size="small">
              {{ getPriorityText(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="publishTime" label="发布时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatTime(row.publishTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="content" label="内容" min-width="300" show-overflow-tooltip />
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button 
              size="small" 
              type="primary" 
              @click="edit(row)"
              :icon="Edit"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(row.id)"
              :icon="Delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <el-empty v-if="!loading && filteredList.length === 0" description="暂无公告" :image-size="150" />
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="isEdit ? '编辑公告' : '新增公告'"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form 
        :model="form" 
        :rules="formRules"
        ref="formRef"
        label-width="100px"
      >
        <el-form-item label="标题" prop="title">
          <el-input 
            v-model="form.title" 
            placeholder="请输入公告标题"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="form.priority" placeholder="请选择优先级" style="width: 100%;">
            <el-option label="普通" :value="0" />
            <el-option label="重要" :value="1" />
            <el-option label="紧急" :value="2" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="内容" prop="content">
          <el-input 
            v-model="form.content" 
            type="textarea" 
            placeholder="请输入公告内容"
            :rows="8"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Bell, Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue';

export default {
  name: 'Announcement',
  components: {
    Bell,
    Plus,
    Search,
    Refresh,
    Edit,
    Delete
  },
  data() {
    return {
      loading: false,
      saving: false,
      list: [],
      searchKeyword: '',
      dialogVisible: false,
      isEdit: false,
      form: {
        title: '',
        content: '',
        priority: 0
      },
      formRules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ],
        priority: [
          { required: true, message: '请选择优先级', trigger: 'change' }
        ]
      }
    };
  },
  computed: {
    filteredList() {
      if (!this.searchKeyword) return this.list;
      const keyword = this.searchKeyword.toLowerCase();
      return this.list.filter(item => 
        (item.title || '').toLowerCase().includes(keyword) ||
        (item.content || '').toLowerCase().includes(keyword)
      );
    }
  },
  async mounted() {
    await this.loadData();
  },
  methods: {
    async loadData() {
      this.loading = true;
      try {
        const res = await axios.get('http://localhost:8080/api/announcements/list');
        if (res.data) {
          this.list = Array.isArray(res.data) ? res.data : [];
        }
      } catch (error) {
        console.error('加载公告列表失败:', error);
        ElMessage.error('加载公告列表失败');
      } finally {
        this.loading = false;
      }
    },
    
    openDialog() {
      this.isEdit = false;
      this.form = {
        title: '',
        content: '',
        priority: 0
      };
      this.dialogVisible = true;
      this.$nextTick(() => {
        if (this.$refs.formRef) {
          this.$refs.formRef.clearValidate();
        }
      });
    },
    
    edit(row) {
      this.isEdit = true;
      this.form = {
        id: row.id,
        title: row.title || '',
        content: row.content || '',
        priority: row.priority !== undefined ? row.priority : 0
      };
      this.dialogVisible = true;
      this.$nextTick(() => {
        if (this.$refs.formRef) {
          this.$refs.formRef.clearValidate();
        }
      });
    },
    
    async handleSave() {
      if (!this.$refs.formRef) return;
      
      try {
        await this.$refs.formRef.validate();
        this.saving = true;
        
        if (this.form.id) {
          // 更新
          await axios.put(`http://localhost:8080/api/announcements/update/${this.form.id}`, this.form);
          ElMessage.success('更新成功');
        } else {
          // 新增
          await axios.post('http://localhost:8080/api/announcements/add', this.form);
          ElMessage.success('新增成功');
        }
        
        this.dialogVisible = false;
        await this.loadData();
      } catch (error) {
        if (error.errors) {
          // 表单验证错误
          return;
        }
        console.error('保存失败:', error);
        ElMessage.error(error.response?.data?.msg || '保存失败');
      } finally {
        this.saving = false;
      }
    },
    
    async handleDelete(id) {
      try {
        await ElMessageBox.confirm(
          '确定要删除这条公告吗？',
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );
        
        await axios.delete(`http://localhost:8080/api/announcements/delete/${id}`);
        ElMessage.success('删除成功');
        await this.loadData();
      } catch (error) {
        if (error === 'cancel') return;
        console.error('删除失败:', error);
        ElMessage.error(error.response?.data?.msg || '删除失败');
      }
    },
    
    handleSearch() {
      // 搜索逻辑已在computed中实现
    },
    
    handleReset() {
      this.searchKeyword = '';
    },
    
    formatTime(time) {
      if (!time) return '-';
      try {
        const date = new Date(time.replace(' ', 'T'));
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}`;
      } catch (error) {
        return time;
      }
    },
    
    getPriorityText(priority) {
      const texts = {
        0: '普通',
        1: '重要',
        2: '紧急'
      };
      return texts[priority] || '普通';
    },
    
    getPriorityType(priority) {
      const types = {
        0: 'info',
        1: 'warning',
        2: 'danger'
      };
      return types[priority] || 'info';
    }
  }
};
</script>

<style scoped>
.announcement-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.main-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-icon {
  font-size: 20px;
  color: #409eff;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
}

/* 表格样式 */
:deep(.el-table) {
  border-radius: 4px;
}

:deep(.el-table__header th) {
  background: #fafafa;
  color: #303133;
  font-weight: 600;
}

:deep(.el-table__row:hover) {
  background: #f5f7fa;
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  padding: 20px 20px 10px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

/* 响应式 */
@media (max-width: 768px) {
  .announcement-page {
    padding: 15px;
  }
  
  .search-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-bar .el-input {
    max-width: 100% !important;
  }
}
</style>
